package com.manage.web.controller;

import com.manage.domain.Emp;
import com.manage.service.IEmpService;
import com.manage.web.editor.LocalDateEditor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.time.LocalDate;
import java.util.List;

@Controller
@RequestMapping("/emp")
public class EmpController {

    @Autowired
    private IEmpService empService;

    @InitBinder
    public void initBinder(WebDataBinder binder) {
        // 处理LocalDate类型的日期绑定
        binder.registerCustomEditor(LocalDate.class, new LocalDateEditor());
    }

    @RequestMapping("/list.do")
    public String list(Model model) {
        List<Emp> list = empService.list();
        model.addAttribute("list", list);
        model.addAttribute("depts", empService.getAllDepts());
        return "emp-list";
    }

    @RequestMapping("/add.do")
    public String add(Emp emp, @RequestParam(required = false) String entryDate, Model model) {
        try {
            // 手动处理日期转换
            if (entryDate != null && !entryDate.trim().isEmpty()) {
                emp.setEntryDate(LocalDate.parse(entryDate));
            }
            System.out.println("接收到的员工数据: " + emp.getName() + ", " + emp.getUsername() + ", " + emp.getGender() + ", " + emp.getDeptId() + ", " + entryDate);
            empService.add(emp);
            return "redirect:/emp/list.do";
        } catch (Exception e) {
            e.printStackTrace();
            model.addAttribute("error", "新增员工失败: " + e.getMessage());
            model.addAttribute("list", empService.list());
            model.addAttribute("depts", empService.getAllDepts());
            return "emp-list";
        }
    }

    @RequestMapping("/update.do")
    public String update(Emp emp, @RequestParam(required = false) String entryDate) {
        try {
            // 手动处理日期转换
            if (entryDate != null && !entryDate.trim().isEmpty()) {
                emp.setEntryDate(LocalDate.parse(entryDate));
            }
            empService.update(emp);
            return "redirect:/emp/list.do";
        } catch (Exception e) {
            e.printStackTrace();
            return "redirect:/emp/list.do?error=" + e.getMessage();
        }
    }

    @RequestMapping("/delete.do")
    public String delete(@RequestParam Integer id) {
        empService.delete(id);
        return "redirect:/emp/list.do";
    }
}


